<?php
class Tag_model extends CI_Model {

    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
    }
    
    function get_all_tags()
    {
        $this->db->select('*');
        $this->db->from('tags');     
        $query = $this->db->get();
        return $query->result('array');  
    }
    
    function get_tag_name($tag_id)
    {
        $this->db->select('name');
        $this->db->from('tags');
        $this->db->where('tag_id', $tag_id);
        $query = $this->db->get();
        return $query->first_row('array');  
    }
    
    function get_tags_by_media_id($media_id)
    {
        $this->db->select('tags.name,tags.tag_id');
        $this->db->join('videos_tags', 'videos_tags.media_id = videos_videos.media_id');
        $this->db->join('tags', 'tags.tag_id = videos_tags.tag_id');
        $this->db->where('videos_tags.media_id', $media_id);
        $this->db->from('videos_videos');     
        $query = $this->db->get();
        return $query->result('array');  
    }
    
    function save_tags($tags)
    {
        for ($i = 0; $i < count($tags); $i = $i + 1)
	{
            $this->db->select('tag_id');
            $this->db->where('name', $tags[$i]);
            $this->db->from('tags');
            $query = $this->db->get();
            $arr_id = $query->result('array');
            if(count($arr_id) > 0)
                continue;
            
            $this->db->set('name', $tags[$i]);
            $this->db->insert('tags'); 
        }
    }  
    
    function attach_tags_to_video($tags, $media_id)
    {
        $this->db->select('tag_id');
        $this->db->where_in('name', $tags);
        $this->db->from('tags');
        $query = $this->db->get();
        $arr_id = $query->result('array');
        
        for ($i = 0; $i < count($arr_id); $i = $i + 1)
	{
            $this->db->set('tag_id', $arr_id[$i]['tag_id']);
            $this->db->set('media_id', $media_id);
            $this->db->insert('videos_tags');
        }
    } 
}
?>